﻿#include "stdafx.h"

#include "ItemViewTools.h"
#include <QHoverEvent>

//======================================================================================================================
QItemViewTools::QItemViewTools(QAbstractItemView * v, QWidget * t, int col) : QObject(v), itemView(v), toolsWidget(t), iColumn(col)
{
	toolsWidget->setParent( itemView->viewport( ) );
	toolsWidget->setVisible( false );
}

void QItemViewTools::showTools( const QModelIndex & index )
{
	currentModelIndex = index;
	emit prepareShow( index );

	QSize toolSize = this->toolsWidget->sizeHint( );
	QRect itemRect = itemView->visualRect( index );
	int margin = ( itemRect.height( ) - toolSize.height( ) ) / 2;
	//int left = itemRect.right( ) - toolSize.width( ) - margin ;
	int left = itemRect.left() + margin;
	int top = itemRect.top( ) + margin;

	this->toolsWidget->move( left , top );
	this->toolsWidget->show( );

	emit showComplete( index );
}

void QItemViewTools::hideTools( )
{
	this->currentModelIndex = QModelIndex( );
	this->toolsWidget->hide( );
}

void QItemViewTools::resize( )
{
	if( currentModelIndex.isValid( ) )
	{
		showTools( currentModelIndex );
	}
}

//======================================================================================================================
QItemViewHoverTools::QItemViewHoverTools(QAbstractItemView * v, QWidget * t ,int col) : QItemViewTools(v, t, col)
{
	itemView->viewport( )->installEventFilter( this );
}

bool QItemViewHoverTools::eventFilter( QObject * obj , QEvent * event )
{
    Q_UNUSED(obj)
	//解决展开树时的闪烁问题。
	if( event->type( ) == QEvent::HoverMove || event->type( ) == QEvent::MouseButtonRelease )
	{
		return hoverMove( ( QHoverEvent * )event );
	}

	if( event->type( ) == QEvent::HoverLeave || event->type( ) == QEvent::MouseButtonPress )
	{
		this->hideTools( );
		return false;
	}
	
	return false;
}

bool QItemViewHoverTools::hoverMove( QHoverEvent * hoverEvent )
{
	QModelIndex index = itemView->indexAt( hoverEvent->pos( ) );
	CHK_EXP_RET( index == currentModelIndex , false );
	if (!index.isValid() || index.column()!=iColumn)
	{
		this->hideTools( );
		return false;
	}

	showTools( index );
	return false;
}

//======================================================================================================================
QItemViewSelectTools::QItemViewSelectTools(QAbstractItemView * v, QWidget * t, int col) : QItemViewTools(v, t,col)
{
	const char * funcPtr = SIGNAL( currentChanged( const QModelIndex & , const QModelIndex & ) );
	const char * slotPtr = SLOT( currentChanged( const QModelIndex & , const QModelIndex & ) );
	connect( this->itemView->selectionModel( ) , funcPtr , this , slotPtr );
}

void QItemViewSelectTools::currentChanged( const QModelIndex & current, const QModelIndex & previous )
{
    Q_UNUSED(previous)
	CHK_EXP_ACT( current.isValid( ) , showTools( current ) , hideTools( ) );
}
